import zk from 'node-zookeeper-client';

/**
 * zookeeper 工具类
 */
class ZkUtil {
    constructor() {

    }

    connect(path) {
        console.log(`start connect ${path}...`);
        let client = zk.createClient(path, null);
        client.connect();
        return client;
    }

    // 获取zk节点数据 （zkClient => 客户端实例，path => zk路径）
    async get(zkClient, path) {
        return new Promise( async (resolve, reject) => {
            let dataArray = [];
            try {
                // path => /infra/services/placeOrder 测试目录
                dataArray = await ZkUtil.getZkChildren(zkClient, path, dataArray);
                resolve(dataArray);
            }catch (error) {
                console.log('get err: ' + error.stack);
                reject(error);
            }

        });

    }

    // 获取zookeeper path下的子目录
    static getZkChildren(zkClient, path, dataArray) {
        return new Promise( (resolve, reject) => {
            zkClient.getChildren(path, async (error, children, stats) => {
                if (error) {
                    zkClient.close();
                    console.log('getChildren err: ' + error.stack);
                    reject(error);
                }
                console.log('Children are: %j.', children);
                for (let i = 0; i < children.length; i++) {
                    let childrenPath = path + '/' + children[i],
                        data = await ZkUtil.getZkData(zkClient, childrenPath);
                    dataArray.push(data.toString()); // data为buffer类型，利用toString函数转化成String类型
                }
                zkClient.close();
                resolve(dataArray);
            });
        });
    }

    // 获取zookeeper指定目录（即childrenPath）下的数据
    static getZkData(zkClient, childrenPath) {
        return new Promise( (resolve, reject) => {
            zkClient.getData(childrenPath, null, (error, data, stat) => {
                if (error) {
                    console.log('getData err: ' + error.stack);
                    reject(error);
                }
                console.log('Got data: %s', data.toString('utf8'));
                resolve(data);
            });
        });
    }


}


let zkUtil = new ZkUtil();

export default zkUtil;
